<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\timer\service;

use app\common\library\helper;
use app\timer\library\Tools;
use app\common\service\BaseService;
use app\timer\model\User as UserModel;
use app\common\model\user\BalanceLog as BalanceLogModel;

/**
 * 服务类：会员等级
 * Class UserGrade
 * @package app\timer\service
 */
class UserBalance extends BaseService
{
    /**
     * 设置用户的会员余额
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setUserBalance()
    {
        // 获取所有会员等级
        $list = $this->getUserList();
        $data = [];
        $date = date('Y-m')."-01"; //每月1号
        foreach ($list as $user) {
            if(!BalanceLogModel::userHasRecharge($user['user_id'],$date)){
                echo "step_1" . PHP_EOL;
                if (!isset($data[$user['user_id']])) {
                    echo "step_2" . PHP_EOL;
                    $data[$user['user_id']] = [
                        'user_id' => $user['user_id'],
                        'money' => 400,//固定400
                        'old_money' => $user['balance'],
                        'date' => $date,
                    ];
                }
            }else{
                echo $date."已存在--".$user['user_id'] . PHP_EOL;
            }
        }
        // 记录日志
        Tools::taskLogs('UserBalance', 'setUserBalance', [
            'data' => $data
        ]);
        // 批量修改会员的余额
        return (new UserModel)->setBatchBalance($data);
    }

    /**
     * 获取所有会员列表
     * @return false|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function getUserList()
    {
        return UserModel::getUserList();
    }
}